from baseview import BaseView
from ..devicetree import DeviceTree
from ..bases import widgets
from .. import editors

class GroupsView(BaseView):
    topwidget_name = 'Groups'
    topwidget_cls = widgets.HPane
    def __init__(self, **kwargs):
        self.topwidget = widgets.HBox()
        super(GroupsView, self).__init__(**kwargs)
        
        self.group_editor = None
        self.group_list = widgets.TreeList(name='Groups', column_names=['id', 'Name'], 
                                           column_order=[1])
        self.update_group_list()
        self.group_list.connect('selection_changed', self.on_group_list_selection_changed)
        
        btnbox = widgets.HBox()
        for key in ['Add', 'Delete']:
            btn = widgets.Button(label=key)
            btnbox.pack_start(btn)
            btn.connect('clicked', self.on_btn_add_delete_clicked, key)
        self.group_list.topwidget.pack_start(btnbox)
        
        self.topcontainer.pack_start(self.group_list.topwidget, expand=True)
        self.topwidget.show_all()
        
        self.MainController.connect('new_group', self.on_mc_new_group)
    
    def unlink(self):
        super(GroupsView, self).unlink()
        for group in self.MainController.Groups.itervalues():
            group.disconnect(callback=self.on_group_property_changed)
    
    def update_group_list(self, key=None):
        if key:
            groups = {key:self.MainController.Groups[key]}
        else:
            groups = self.MainController.Groups
        for key, val in groups.iteritems():
            if 'MainController_' not in key:
                self.group_list.update({key:val.name})
                val.connect('property_changed', self.on_group_property_changed)
            
    def set_current_group(self, group):
        if self.group_editor:
            self.remove_editor(self.group_editor)
        self.add_editor(editors.GroupEditor, 'group_editor', group=group)
        self.topcontainer.pack_start(self.group_editor.topwidget, expand=True)
        
    def on_group_list_selection_changed(self, **kwargs):
        key = kwargs.get('key')
        group = self.MainController.Groups[key]
        self.set_current_group(group)
        
    def on_mc_new_group(self, **kwargs):
        key = kwargs.get('id')
        self.update_group_list(key)
        group = self.MainController.Groups[key]
        group.connect('property_changed', self.on_group_property_changed)
        
    def on_btn_add_delete_clicked(self, btn, key):
        if key == 'Add':
            group = self.MainController.add_group(name='New Group')
            self.update_group_list(group.id)
            self.group_list.set_current_selection(key=group.id)
            self.set_current_group(group)
        elif key == 'Delete':
            pass
            
    def on_group_property_changed(self, **kwargs):
        obj = kwargs.get('obj')
        self.update_group_list(obj.id)
        
